<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-select v-model="listQuery.idcId" placeholder="请选择机房" class="filter-item" clearable filterable >
        <el-option v-for="item in idcOptions" :key="item.id" :label="item.name" :value="item.id"/>
      </el-select>
      <el-input v-model="listQuery.ip" placeholder="内(公)网IP" class="filter-item" clearable style="width: 150px"/>
      <el-input v-model="listQuery.hostName" placeholder="主机名" class="filter-item" clearable style="width: 150px"/>
      <el-select v-model="listQuery.env" clearable filterable placeholder="请选择应用环境" class="filter-item">
        <el-option v-for="item in envOptions" :key="item.name" :label="item.name" :value="item.name"/>
      </el-select>
      <el-input v-model="listQuery.purpose" placeholder="主机功能" class="filter-item" clearable style="width: 150px" />
      <el-select v-model="listQuery.clusterName" placeholder="请选择集群" class="filter-item" clearable filterable >
        <el-option v-for="(item, index) in clusterOptions" :key="index" :label="item" :value="item"/>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-menu" @click="goCabinetDeploymentView">机柜部署图</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="exportA">导出</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" element-loading-text="加载中" border fit highlight-current-row style="width: 100%">
      <el-table-column width="80px" align="center" label="集群">
        <template slot-scope="scope">
          <span>{{ scope.row.clusterName }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="内网IP">
        <template slot-scope="scope">
          <span :title="scope.row.ip"> {{ scope.row.ip }} </span>
          <div v-if="scope.row.intranetIP.length > 0">
            <p v-for="item in scope.row.intranetIP" :key="item.key"><el-tag style="width:100%">{{ item.name }}</el-tag></p>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="130px" align="center" label="公网IP">
        <template slot-scope="scope">
          <span>{{ scope.row.ipPublic }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="主机名">
        <template slot-scope="scope">
          <span>{{ scope.row.host }}</span>
        </template>
      </el-table-column>
      <el-table-column width="140px" align="center" label="配置">
        <template slot-scope="scope">
          <span>{{ scope.row.numCpus }}c/{{ scope.row.memTotal/1024 | roundUp }}g/{{ scope.row.diskCapacity }}g</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="CPU颗数/总插槽">
        <template slot-scope="scope">
          <span>{{ scope.row.cpuGrainNum }}/{{ scope.row.cpuSlotNum }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" align="center" label="内存条数量/总插槽">
        <template slot-scope="scope">
          <span>{{ scope.row.memNum }}/{{ scope.row.memSlotNum }}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="硬盘数量/总插槽">
        <template slot-scope="scope">
          <span>{{ scope.row.diskNum }}/{{ scope.row.diskSlotNum }}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="电源数量/总插槽">
        <template slot-scope="scope">
          <span>{{ scope.row.powerNum }}/{{ scope.row.powerSlotNum }}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="网口数量/总数">
        <template slot-scope="scope">
          <span>{{ scope.row.netNum }}/{{ scope.row.netNum + scope.row.netUseNum }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="机房">
        <template slot-scope="scope">
          <span>{{ scope.row.rackName }}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{ statusDict[scope.row.istatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="90px" label="备注">
        <template slot-scope="scope">
          <span>{{ scope.row.comment }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" fixed="right" align="center" width="260px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <!-- 新增|修改 Start -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="1000px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 900px; margin-left:5px;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="服务器规格" prop="serverSpec">
              <el-select :disabled="dialogStatus == 'update'" v-model="temp.serverSpec" class="filter-item" value-key="id" placeholder="请选择服务器规格" @change="updateCurrentTemp">
                <el-option v-for="item in serverOptions" :key="item.id" :label="item.name" :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内网IP" prop="ip">
              <el-input v-model="temp.ip"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公网IP">
              <el-input v-model="temp.ipPublic"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="主机名" prop="host">
              <el-input v-model="temp.host"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主机功能" prop="purpose">
              <el-input v-model="temp.purpose"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="CPU核数" prop="numCpus">
              <el-input-number v-model="temp.numCpus" :min="1" :max="999999999" controls-position="right" style="width:180px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="内存大小(MB)" prop="memTotal">
              <el-input-number v-model="temp.memTotal" :min="1024" :step="1024" :max="999999999" controls-position="right" style="width:180px"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="硬盘大小(G)" prop="diskCapacity">
              <el-input-number v-model="temp.diskCapacity" :min="1" :max="999999999" controls-position="right" style="width:180px"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机房" prop="idcId">
              <el-select v-model="temp.rackName" class="filter-item" value-key="id" placeholder="请选择机房" @change="getCabinetList">
                <el-option v-for="item in idcOptions" :key="item.id" :label="item.name" :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="SN序列号" prop="systemSerialnumber">
              <el-input v-model="temp.systemSerialnumber"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="istatus">
              <el-select v-model="temp.istatus" class="filter-item" placeholder="请选择状态">
                <el-option v-for="item in istatusOptions" :key="item.key" :label="item.label" :value="item.key"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务器型号" prop="productname">
              <el-input v-model="temp.productname"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="CPU型号" prop="cpuModel">
              <el-input v-model="temp.cpuModel"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="CPU颗数" prop="cpuGrainNum">
              <el-input v-model="temp.cpuGrainNum" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="CPU插槽数" prop="cpuSlotNum">
              <el-input v-model="temp.cpuSlotNum" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="内存型号" prop="memModel">
              <el-input v-model="temp.memModel"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内存数量" prop="memNum">
              <el-input v-model="temp.memNum" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内存插槽数" prop="memSlotNum">
              <el-input v-model="temp.memSlotNum" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="硬盘型号" prop="diskModel">
              <el-input v-model="temp.diskModel"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="硬盘数量" prop="diskNum">
              <el-input v-model="temp.diskNum" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="硬盘插槽数" prop="diskSlotNum">
              <el-input v-model="temp.diskSlotNum" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="电源型号" prop="powerModel">
              <el-input v-model="temp.powerModel"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电源数量" prop="powerNum">
              <el-input v-model="temp.powerNum" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电源插槽数" prop="powerSlotNum">
              <el-input v-model="temp.powerSlotNum" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="网口数量" prop="netNum">
              <el-input v-model="temp.netNum" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网口已用数量" prop="netUseNum">
              <el-input v-model="temp.netUseNum" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所在机柜" prop="cabinetName">
              <el-select v-model="temp.cabinetName" class="filter-item" value-key="id" placeholder="请选择机柜" @change="selectCabinet" @focus="focusCabinet">
                <el-option v-for="item in cabinetOptions" :key="item.id" :label="item.name" :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属集群" prop="clusterName">
              <el-select v-model="temp.clusterName" class="filter-item" placeholder="请选择集群">
                <el-option v-for="item in clusterOptions" :key="item" :label="item" :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="U数" prop="udesc">
              <el-input v-model="temp.udesc" :min="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="U的位置" prop="uposition">
              <el-input v-model="temp.uposition" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="操作系统" prop="os">
              <el-input v-model="temp.os"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作系统版本" prop="osrelease">
              <el-input v-model="temp.osrelease"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定资产编号" prop="assetNumber">
              <el-input v-model="temp.assetNumber"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="minitor ID" prop="hostName">
              <el-input v-model="temp.hostName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购日期" prop="purchaseDate">
              <el-date-picker v-model="temp.purchaseDate" type="date" placeholder="选择采购日期" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保修到期" prop="periodDate">
              <el-date-picker v-model="temp.periodDate" type="date" placeholder="选择保修到期" style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="RAID信息" prop="raidInfo">
              <el-input v-model="temp.raidInfo"/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="comment">
              <el-input :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.comment" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
        <el-button v-if="dialogStatus == 'create'" type="success" @click="saveNextData">{{ $t('table.saveNext') }}</el-button>
      </div>
    </el-dialog>
    <!-- 新增|修改 End -->

    <!-- 主机详情 Start -->
    <el-dialog :visible.sync="dialogDetailVisible" title="主机详情" width="1000px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 900px; margin-left:5px;">
        <el-row>
          <el-col :span="8">
            <el-form-item label="主机">
              <el-input v-model="temp.hostName" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购日期">
              <el-input v-model="temp.purchaseDate" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保修到期">
              <el-input v-model="temp.periodDate" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="服务器型号">
              <el-input v-model="temp.productname" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SN序列号">
              <el-input v-model="temp.systemSerialnumber" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定资产编号">
              <el-input v-model="temp.assetNumber" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="操作系统">
              <el-input v-model="temp.osNew" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="kernel版本">
              <el-input v-model="temp.kernelRelease" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="CPU型号">
              <el-input v-model="temp.cpuModel" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="机柜">
              <el-input v-model="temp.cabinetName" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="u数">
              <el-input v-model="temp.udesc" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="salt版本">
              <el-input v-model="temp.saltversion" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-input v-model="temp.createTimeStr" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间">
              <el-input v-model="temp.updateTimeStr" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部署分组">
              <el-input v-model="temp.groupName" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="创建人">
              <el-input v-model="temp.creator" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新人">
              <el-input v-model="temp.updator" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 主机详情 End -->
  </div>
</template>
<script>
import {
  fetchList,
  // fetchPhysicalHostList,
  fetchIdc,
  // fetchDevList,
  fetchEnv,
  update,
  insert,
  del,
  fetchClusterList,
  fetchCabinetList,
  fetchServerSpec
} from '@/api/bareMachine'
import { getToken } from '@/utils/auth'
import { generateSign } from '@/utils/signature'

export default {
  name: 'ComplexTable',
  filters: {
    roundUp: function(number) {
      if (!number || Math.round(number) === number) {
        return number
      }
      return number.toFixed(2)
    }
  },
  data() {
    var checkIp = (rule, value, callback) => {
      const reg = /^[[\s\S]{1,}]$/
      if (!reg.test(value)) {
        callback(new Error('请按照此格式[1.1.1.1]输入'))
      } else {
        callback()
      }
    }
    return {
      // 格式化主机
      formatIP: function(content) {
        if (!content) {
          return ''
        }
        const strList = []
        if (content.indexOf(',') !== -1) {
          content = content.replace(/\[|]/g, '')
          const contentList = content.split(',')
          for (let a = 0; a < contentList.length; a++) {
            contentList[a] = contentList[a].replace(/^\s+|\s+$/g, '')
            const temp = {
              key: a,
              name: '[' + contentList[a] + ']'
            }
            strList.push(temp)
          }
        } else {
          strList[0] = {
            key: 1,
            name: content
          }
        }
        return strList
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        idcId: '', // 机房id
        relativeHost: '', // 宿主机
        env: '', // 应用环境
        ip: '', // 内(公)网IP
        purpose: '', // 主机功能
        hostName: '', // 主机名
        clusterName: '', // 集群名称
        page: 1,
        limit: 10
      },
      // 条件筛选主机状态
      istatusOptions: [
        { label: '闲置', key: 0 },
        { label: '在用', key: 1 },
        { label: '故障', key: 2 },
        { label: '报废', key: 3 }
      ],
      // 主机类型
      hostTypeOptions: ['physical', 'VMware', 'kvm', 'hype-v'],
      // 部署分组
      groupOptions: ['A', 'B'],
      // 主机状态
      statusDict: {
        0: '闲置',
        1: '在用',
        2: '故障',
        3: '报废'
      },
      idcOptions: [], // 机房
      // devOptions: [],  // 负责人
      // hostOptions: [], // 宿主机
      envOptions: [], // 应用环境
      clusterOptions: [], //  集群
      serverOptions: [], // 服务器规格
      cabinetOptions: [], // 机柜
      temp: {
        id: undefined,
        ip: '', // 内网IP
        ipPublic: '', // 公网IP
        host: '', // 主机名
        purpose: '', // 主机功能
        numCpus: '1', // CPU颗数
        memTotal: '', // 内存大小
        diskCapacity: '40', // 硬盘大小
        idcId: '', // 机房ID
        rackName: '', // 机房名称
        systemSerialnumber: '', // SN序列号
        istatus: 1, // 状态
        productname: '', // 服务器型号
        cpuModel: '', // CPU型号
        cpuGrainNum: '', // CPU颗数
        cpuSlotNum: '', // CPU插槽数
        memModel: '', // 内存型号
        memNum: '', // 内存数量
        memSlotNum: '', // 内存插槽数
        diskModel: '', // 硬盘型号
        diskNum: '', // 硬盘数量
        diskSlotNum: '', // 硬盘插槽数
        powerModel: '', // 电源型号
        powerNum: '', // 电源数量
        powerSlotNum: '', // 电源插槽数
        netNum: '', // 网口数量
        netUseNum: '', // 网口已用数量
        cabinetId: '', // 机柜ID
        cabinetName: '', // 机柜名称
        clusterName: '', // 集群名称
        udesc: '', // U数
        uposition: '', // U的位置
        os: 'CentOS', // 操作系统
        osrelease: '6.9', // 操作系统版本
        assetNumber: '', // 固定资产编号
        hostName: '', // minitor ID
        purchaseDate: '', // 采购日期
        periodDate: '', // 保修到期
        raidInfo: '', // RAID信息
        comment: '' // 备注
        // type: "",  // 主机类型
        // relativeHost: "",  // 宿主机
        // env: "",  // 应用环境
        // manager: "",  // 负责人
        // kernelRelease: "2.6.32-504.el6.x86_64",  // 系统内核版本
        // saltversion: "",  // salt版本
        // groupName: "", // 部署分组
        // createTime: "",  // 创建时间
        // updateTime: "",  // 更新时间
        // createTimeStr: "", // 创建时间
        // updateTimeStr: "",  // 更新时间
        // updator: "",  // 更新人
        // creator: "",  // 创建人
        // osNew: "",  // 新操作系统
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      dialogDetailVisible: false,
      rules: {
        hostName: [
          { required: true, message: '主机是必填项', trigger: 'blur' }
        ],
        os: [{ required: true, message: '操作系统是必填项', trigger: 'blur' }],
        osrelease: [
          { required: true, message: '操作系统版本是必填项', trigger: 'blur' }
        ],
        memTotal: [
          { required: true, message: '内存大小是必填项', trigger: 'blur' }
        ],
        numCpus: [
          { required: true, message: 'CPU核数是必填项', trigger: 'blur' }
        ],
        purpose: [
          { required: true, message: '主机功能是必填项', trigger: 'blur' }
        ],
        host: [{ required: true, message: '主机名是必填项', trigger: 'blur' }],
        type: [
          { required: true, message: '主机类型是必填项', trigger: 'blur' }
        ],
        ip: [
          { required: true, message: '内网IP是必填项', trigger: 'blur' },
          { validator: checkIp, trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  watch: {
    dialogFormVisible: function(val) {
      if (!val) {
        for (const item in this.temp) {
          this.temp[item] = ''
        }
      }
    }
  },
  created() {
    this.getList() // 获取裸机列表
    this.getEnvOptions() // 获取应用环境
    this.getIdcList() // 获取机房列表
    this.getClusterList() // 获取集群列表
    // this.getHostList(); // 获取宿主机列表
    // this.getDevList();  // 获取负责人列表
  },
  methods: {
    // 获取裸机列表
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        const recordsList = response.data.records
        if (recordsList.length > 0) {
          for (let a = 0; a < recordsList.length; a++) {
            recordsList[a].intranetIP = this.formatIP(recordsList[a].ip)
          }
        }
        this.list = recordsList
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 获取集群名称列表
    getClusterList() {
      fetchClusterList().then(response => {
        this.clusterOptions = response.data
      })
    },
    // 获取应用环境列表
    getEnvOptions() {
      fetchEnv().then(response => {
        this.envOptions = response.data
      })
    },
    // 获取宿主机列表
    // getHostList() {
    //   fetchPhysicalHostList().then(response => {
    //     this.hostOptions = response.data;
    //   });
    // },
    // 获取机房列表
    getIdcList() {
      fetchIdc().then(response => {
        this.idcOptions = response.data.records
      })
    },
    // 获取负责人列表
    // getDevList() {
    //   fetchDevList().then(response => {
    //     this.devOptions = response.data;
    //   });
    // },
    // 跳转到机柜部署图
    goCabinetDeploymentView() {
      location.href = '#/cmdb/cabinetDeployment'
    },
    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 服务器规格
    getServerSpecList() {
      fetchServerSpec().then(response => {
        this.serverOptions = response.data
      })
    },
    // 机柜列表
    getCabinetList(item) {
      this.temp.idcId = item.id
      this.temp.rackName = item.name
      const queryCabinet = {
        idcId: item.id
      }
      if (!(item.isUpdate && item.isUpdate === true)) {
        this.temp.cabinetName = ''
        this.temp.cabinetId = ''
      }
      fetchCabinetList(queryCabinet).then(response => {
        this.cabinetOptions = response.data
      })
    },
    // 赋值
    selectCabinet(item) {
      this.$forceUpdate() // 数据层次太多，没有触发render函数进行自动更新,需手动调用
      this.temp.cabinetName = item.name
      this.temp.cabinetId = item.id
    },
    // 并且没有优先选择机房，选择机柜时
    focusCabinet() {
      if (!this.temp.idcId) {
        this.$notify.info({
          title: '消息',
          message: '请先选择机房'
        })
      }
    },
    // 导出Excel数据
    exportA() {
      var url = process.env.BASE_API + '/api/hostBare/export'
      var keys = [
        'env',
        'token',
        'sign',
        'appCode',
        'purpose',
        'appEnv',
        'idcId',
        'ip',
        'hostName',
        'clusterName'
      ]
      var values = [
        process.env.ENV_ROUTE,
        getToken(),
        generateSign(process.env.KEY, process.env.APP_CODE),
        process.env.APP_CODE,
        this.listQuery.purpose,
        this.listQuery.env,
        this.listQuery.idcId,
        this.listQuery.ip,
        this.listQuery.hostName,
        this.listQuery.clusterName
      ]
      this.openWindowWithPost(url, keys, values)
    },
    openWindowWithPost(url, keys, values) {
      var oForm = document.createElement('form')
      oForm.method = 'GET'
      oForm.action = url
      if (keys && values && keys.length === values.length) {
        for (var i = 0; i < keys.length; i++) {
          var oInput = document.createElement('input')
          oInput.type = 'text'
          oInput.name = keys[i]
          oInput.value = values[i]
          oForm.appendChild(oInput)
        }
      }
      oForm.onSubmit = function() {
        window.open(url)
      }
      document.body.appendChild(oForm)
      oForm.submit()
      document.body.removeChild(oForm)
    },
    // 每页条数
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    // 当前页数
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 删除数据
    handleDelete(row) {
      this.$confirm('此删除操作不可还原, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del({ 'ihostId': row.ihostId }).then(response => {
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(() => {})
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        comment: ''
      }
    },
    // 添加数据
    handleCreate() {
      this.getServerSpecList()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 详情
    handleDetail(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogDetailVisible = true
    },

    // 编辑数据
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.getCabinetList({ 'id': row.idcId, 'name': row.rackName, 'isUpdate': true })
      this.temp.rackName = row.rackName
      this.temp.idcId = row.idcId
      this.temp.cabinetName = row.cabinet
      this.temp.cabinetId = row.cabinetId

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 确定保存已更改数据
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 创建数据操作
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          insert(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 根据服务器规格进行初始化
    updateCurrentTemp(obj) {
      this.temp = Object.assign({}, obj)
      // for (let item in obj) {
      //   for(let t in this.temp) {
      //     if (item == t) {
      //       this.temp[t] = obj[item];
      //     }
      //   }
      // }
      this.temp.serverSpec = obj.name
      this.temp.id = undefined
    },
    // 保存新增数据并转到下一条
    saveNextData() {
      this.createData()
    }
  }
}
</script>
